﻿using System;
using System.Web.Mvc;
using WeBlog.DataContext;
using WeBlog.Models;
using WeBlog.Resources;
using WeBlog.Services;

namespace WeBlog.Controllers
{
    public class SetupController : Controller
    {        
        public ActionResult Index()
        {
            var model = new SetupViewModel();
            return View( model );
        }

        [HttpPost]
        public ActionResult Index(SetupViewModel model)
        {
            if (model.StorageOptionId == StorageOptions.SqlServer && String.IsNullOrWhiteSpace(model.SqlConnectionString))            
                ModelState.AddModelError("SqlConnectionString", Strings.Required);
            
            if( model.Password != model.ConfirmPassword)
                ModelState.AddModelError("Password", Strings.Account_PasswordsDoNotMatch);
        
            if (ModelState.IsValid)
            {             
                InitializeDatabase(model);                                
                return RedirectToAction("Index","Post");
            }

            return View(model);
        }


        private void InitializeDatabase(SetupViewModel model)
        {
            if (model.StorageOptionId == StorageOptions.SqlServer)
            {
                model.Config.ConnectionString = model.SqlConnectionString;
                model.Config.ProviderName = "System.Data.SqlClient";
            }
            //sql compact connection string
            else
            {
                model.Config.ConnectionString = string.Format(
					"Data Source=|DataDirectory|Sites\\{0}\\WeBlog.sdf",
					model.Config.Id);
                model.Config.ProviderName = "System.Data.SqlServerCe.4.0";
            }

            SiteManager.Save(model.Config);            
            var unitOfWork = new WeBlogContext();

            var user = new User
            {
                FirstName = "Admin",
                LastName = "Account",
                Email = model.AdminEmail,
                RoleFlag = RoleValues.Admin,
                Password = model.ConfirmPassword,
                Activated = true
            };            
            unitOfWork.Users.Add(user);

            var post = new Post
            {
                Title = Strings.Setup_Welcome,
                Author = user,
                Content = Strings.Welcome_Post,
                Slug = "welcome-to-weblog",
                PublishDate = DateTime.Now,
                Published = true,
                LastModified = DateTime.Now
            };
            unitOfWork.Posts.Add(post);
            unitOfWork.Save();
        }        
    }
}
